package service

import (
	fs "multimedia/FsEvent"
	"multimedia/WSService"
	"multimedia/conf"
	"multimedia/dbimpl"
	"multimedia/utils"
	"multimedia/whiteboard"
	"net/http"

	"github.com/gin-gonic/gin"
	log "github.com/sirupsen/logrus"
)

var DataSrv *Srv

type Srv struct {
	mysql        *dbimpl.MysqlImpl
	redis        *dbimpl.RedisImpl
	TLSSig       *utils.TLSSigUtils
	roomIdCreate *utils.RoomIdCreate
	Recordlist   *RecordMgr
	recordsrv    *whiteboard.RecordConnSrv
	wsClient     *WSService.Hub
	fsCli        *fs.FSClient
	fsEvent      *fs.FSClient
}

func init() {
	DataSrv = New(&conf.ConfigFile)
}
func New(con *conf.Config) *Srv {
	s := &Srv{
		TLSSig:       utils.NewTLSSig(),
		roomIdCreate: utils.NewRoomIdCreat(),
		fsCli:        fs.New(con.FSConf.FSAddr, con.FSConf.FSPassWord),
		fsEvent:      fs.New(con.FSConf.FSAddr, con.FSConf.FSPassWord),
		Recordlist:   NewRecordMgr(),
	}
	s.mysql = dbimpl.NewMysql(con.MysqlCon)
	if s.mysql == nil {
		log.WithField("func:", "Service New").Errorf("service new mysql error")
		return nil
	}
	redis, err := dbimpl.NewRedis("", con.RedisCon)
	if err != nil {
		log.WithField("func:", "Service New").Errorf(err.Error())
		return nil
	}
	if redis == nil {
		log.WithField("func:", "Service New").Errorf("service new redis error")
		return nil
	}
	s.redis = redis
	s.wsClient = WSService.New(s.mysql, s.redis)
	err = s.fsCli.Connect()
	if err != nil {
		log.WithField("func:", "Service New").Errorf("new fsclient error the msg is:%s", err.Error())
		return nil
	}
	err = s.fsEvent.Connect()
	if err != nil {
		log.WithField("func:", "Service New").Errorf("new fsclient error the msg is:%s", err.Error())
		return nil
	}
	s.recordsrv = whiteboard.New()
	go s.fsEvent.OnEvent()
	go s.ProcessEvent()
	return s
}

func (s *Srv) HandleRequest(w http.ResponseWriter, r *http.Request, c *gin.Context) {
	userId := c.Param("userId")
	s.wsClient.HandleRequest(w, r, userId)
}

func (s *Srv) WhiteBoardRecord(w http.ResponseWriter, r *http.Request, c *gin.Context) {
	filename := c.Param("filename")
	s.recordsrv.HandleRequest(w, r, filename)
}
